<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model.trim="header.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="List">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/park/add')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="tableList" @expand-change="expandHandle">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentlist">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="obj">
                  <el-tag :type="formatInfoType(obj.row.status)">
                    {{ formatStatus(obj.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="arr">
                  <el-button size="mini" type="text" @click="outRent(arr.row.id)">退租</el-button>
                  <el-button size="mini" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button size="mini" type="text" @click="openContract(row)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/enterpriseDetail/?id=${row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/park/add/?id=${row.id}`)">编辑</el-button>
            <el-button size="mini" type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="+total"
        :page-size="header.pageSize"
        layout="total, prev, pager, next"
        @current-change="pageChange"
      />
    </div>
    <el-dialog
      class="custom-dialog"
      title="添加"
      :visible.sync="dialogVisible"
      width="40%"
      :close="handleClose"
    >
      <el-form ref="addform" :model="addform" :rules="rentRules" class="dialog">

        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="addform.buildingId" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="rentTime">
          <span>租赁起止时间</span>
          <el-date-picker
            v-model="addform.rentTime"
            style="width: 100%;"
            type="daterange"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-form-item>

        <el-form-item prop="contractId">
          <span>租赁合同</span>
          <!-- accept=".doc,.docx,.jpg"控制上传类型 -->
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="uploadChange"
          >
            <el-button size="small" type="primary" plain>上传合同文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <!-- 编辑查看回显 回显图片 -->
          <!-- <img :src="addForm.contractUrl" alt="" width="100"> -->
          <!-- 回显图片 -->
          <!-- <img v-show="id" :src="addForm.businessLicenseUrl" alt="" width="100"> -->
        </el-form-item>

      </el-form>
      <span slot="footer" class="el-dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getList, delList, getRentListAPI, getRentBuildListAPI, createRentAPI, outRentApi } from '@/api/enterprise'
import { update } from '@/api/add'
export default {
  name: 'EnterpricePage',
  data() {
    return {
      buildingList: [],
      dialogVisible: false,
      header: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      tableList: [],
      total: '',
      addform: {
        contractId: '',
        contractUrl: '',
        rentTime: [],
        buildingId: '',
        type: 0,
        enterpriseId: ''
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      }
    }
  },
  created() {
    this.List()
  },
  methods: {
    async getRent() {
      const { data } = await getRentListAPI(this.curEnter.id) // 当前更新
      this.curEnter.rentlist = data
    },
    // 退租
    async outRent(id) {
      // 用户确认
      // 确认后，调用退租api
      // 刷新当前公司下的合同列表
      try {
        await this.$confirm('确认退租吗？', '提示')
        await outRentApi(id)
        console.log(this.curEnter.id)
        this.getRent()
        this.$message.success('退租成功')
      } catch (error) {
        console.log(error, '退租')
      }
    },
    // 兜底校验
    async submitAdd() {
      try {
        await this.$refs.addform.validate()
        const { buildingId, contractId, contractUrl, enterpriseId, type } = this.addform
        await createRentAPI({
          buildingId, contractId, contractUrl, enterpriseId, type,
          startTime: this.addform.rentTime[0],
          endTime: this.addform.rentTime[1]
        })
        // 更新列表
        // this.List()
        this.handleClose()
        // 刷新当前添加公司下的合同列表
        this.getRent()

        this.$message.success('添加成功')
      } catch (error) {
        console.log(222, error)
      }
    },
    // 格式化tag类型
    formatInfoType(type) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[type]
    },
    // 状态
    formatStatus(status) {
      const Status = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return Status[status]
    },
    async expandHandle(currRow, row) {
      const isExpand = row.some(item => item.id === currRow.id)
      if (isExpand) {
        const { data } = await getRentListAPI(currRow.id)
        // console.log(res)
        // eslint-disable-next-line require-atomic-updates
        // currRow.rentlist = data
        // vue2.6存在的bug：对象中没有定义的属性或者使用数组的下标修改值，不会触发响应式
        // 解决 this.$set()
        this.$set(currRow, 'rentlist', data)
      }
    },

    async uploadChange(data) {
      // 实例化对象
      const fm = new FormData()
      fm.append('file', data.file) // 添加实例
      fm.append('type', 'contract') // 添加实例
      const res = await update(fm)
      this.$message.success('上传成功')
      this.addform.contractId = res.data.id
      this.addform.contractUrl = res.data.url

      this.$refs.addform.validateField('contractId')// validateField清除校验字段
    },

    handleClose() {
      this.dialogVisible = false
      this.$refs.addform.resetFields()
    },

    // 添加合同点击
    async openContract(row) {
      this.dialogVisible = true
      // 查询楼宇信息，供用户选择
      const res = await getRentBuildListAPI()
      this.buildingList = res.data
      this.addform.enterpriseId = row.id
      // 存储当前的公司信息
      this.curEnter = row
    },
    async List() {
      const res = await getList(this.header)
      // console.log(res)
      // 使用map为tableList下面的每一项添加rentList
      this.tableList = res.data.rows.map(item => {
        return {
          ...item,
          rentlist: []
        }
      })
      this.total = res.data.total
    },
    // 改变
    pageChange(val) {
      this.header.page = val
      this.List()
    },
    // 点击删除
    del(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delList(id)
        this.List()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}

.el-dialog__footer {
  background-color: #5ABEF2 !important;

}

.dialog{
  margin-left: 80px;
  margin-right: 80px;
}

.el-icon-date{
  transform: translateX(50px);
}

</style>
